package com.lingyue.entity.validator;

import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;

/**
 * @version 1.0.0
 * @author: lzy
 * @date: 2019/6/19 15:03
 */
public class ValidateUtils {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 校验实体
     * @param object
     * @param group
     * @return
     */
    public static String validate(Object object, Class group){
        if(null == object){
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        Set<ConstraintViolation<Object>> validate = validator.validate(object, group);
        if(validate.isEmpty()){
            return "";
        }
        validate.forEach(item ->{
            if(stringBuilder.length() > 1){
                stringBuilder.append("、");
            }
            if(StringUtils.isEmpty(item.getMessage())) {
                stringBuilder.append(item.getPropertyPath().toString());
            } else {
                stringBuilder.append(item.getMessage());
            }
        });
        return stringBuilder.toString();
    }

    /**
     * 校验实体
     * @param object
     * @return
     */
    public static String validate(Object object){
        return validate(object, Default.class);
    }

}
